package edu.neelsys.mvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import edu.neelsys.business.userauth.UserService;
import edu.neelsys.mvc.util.Constants;
import edu.neelsys.mvc.util.ErrorMessage;
import edu.neelsys.objectmodel.dbentites.User;
import edu.neelsys.objectmodel.userauth.LoggedUser;

/*
 * RegistrationController handles user
 * creation functionality. User is created using username(required),
 * password(required)
 * and email(optional)
 */

public class UserUpdateController extends SimpleFormController {

	private UserService userService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax
	 * .servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
	 * java.lang.Object, org.springframework.validation.BindException) User is
	 * created using username(required), password(required) and email(optional)
	 */
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {

		LoggedUser loggedUser = (LoggedUser) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		User usr = loggedUser.getUser();
		userService.updateUser(usr);
		System.out.println("welcome");
		String errorMessage = ErrorMessage.message;
		ErrorMessage.message = null;
		if (errorMessage != null) {
			ObjectError oerr = new ObjectError(errorMessage, errorMessage);
			errors.addError(oerr);
			ModelAndView mav = new ModelAndView(Constants.UPDATE_VIEW,
					Constants.LOGIN_FORM_MODEL, usr);
			mav.addObject(errors);
			return mav;
		} else {

			ModelAndView successmav = new ModelAndView(getSuccessView(),
					Constants.LOGIN_FORM_MODEL, usr);
			successmav.addObject(usr);
			return successmav;
		}
	}
}
